package com.qd.panda.service.stroke;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.panda.domain.entity.stroke.UserStrokeHistoryDTO;
import com.qd.common.panda.domain.entity.stroke.WebUserStrokeDTO;
import com.qd.panda.mapper.stroke.UserStrokeHistoryMapper;
import com.qd.panda.model.CarPark;
import com.qd.panda.model.CarParkLocation;
import com.qd.panda.model.UserStrokeHistory;
import com.qd.panda.model.UserStrokeProcessDetail;
import com.qd.panda.service.park.CarParkLocationService;
import com.qd.panda.service.park.CarParkService;
import com.qd.system.service.user.UserOperatorService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 用户行程历史记录
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserStrokeHistoryService extends BaseService<UserStrokeHistoryMapper, UserStrokeHistory> {

    private static final String TRIP_TYPE = "trip_type";
    private static final Integer DEFAULT_TRIP_TYPE = 999999;
    private static final String PREFIX_ID = "panda_user_stroke_history_sid_{0}";

    private static final String PREFIX_USER_ID = "panda_user_stroke_history_last_userId_{0}_tripType_{1}";

    private final RedisTemplateUtil<UserStrokeHistory> redisTemplateUtil;

    private final CarParkService carParkService;
    private final CarParkLocationService carParkLocationService;

    private final UserStrokeProcessDetailService userStrokeProcessDetailService;

    private final ObjectMapper objectMapper;


    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeHistoryDTO save(UserStrokeHistoryDTO dto) {
        final UserStrokeHistory model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeHistoryDTO update(UserStrokeHistoryDTO dto) {
        final UserStrokeHistory historyModel = Optional.ofNullable(getById(dto.getSid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserStrokeHistory model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param sid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String sid) {
        final UserStrokeHistory model = Optional.ofNullable(getById(sid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(sid)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserStrokeHistoryDTO dto) {
        final QueryWrapper<UserStrokeHistory> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param sid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String sid) {
        boolean exists = false;
        if (StringUtils.hasLength(sid)) {
            final UserStrokeHistory model = getById(sid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param sid 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeHistory getById(String sid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, sid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(sid), UserStrokeHistory.class);
    }

    /**
     * 获取用户最后一次行程记录
     *
     * @param userId   用户ID
     * @param tripType 0停车1充电，不传就查询停车和充电的行程
     * @return 停车记录
     */
    @Transactional(readOnly = true)
    public UserStrokeHistoryDTO getLastDto(String userId, Integer tripType) {
        if (null == tripType) {
            tripType = DEFAULT_TRIP_TYPE;
        }
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, userId, tripType);
        Integer finalTripType = tripType;
        final UserStrokeHistory model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> {
            QueryWrapper<UserStrokeHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            if (finalTripType.equals(DEFAULT_TRIP_TYPE)) {
                queryWrapper.in(TRIP_TYPE, DisplayUtil.TRIP_TYPE_0, DisplayUtil.TRIP_TYPE_1);
            } else {
                queryWrapper.eq(TRIP_TYPE, finalTripType);
            }
            if (finalTripType.equals(DEFAULT_TRIP_TYPE)) {
                queryWrapper.orderByDesc("start_time");
            } else if (finalTripType.equals(DisplayUtil.TRIP_TYPE_0)) {
                queryWrapper.orderByDesc("appointment_time");
            } else {
                queryWrapper.orderByDesc("start_time");
            }
            queryWrapper.last("limit 1");
            UserStrokeHistory userStrokeHistory = getOne(queryWrapper, false);
            queryWrapper.clear();
            return userStrokeHistory;
        }, UserStrokeHistory.class);
        return Optional.ofNullable(model).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据主键获取数据
     *
     * @param sid 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeHistoryDTO getByIdDto(String sid) {
        return Optional.ofNullable(getById(sid)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeHistory getOne(UserStrokeHistoryDTO dto) {
        final QueryWrapper<UserStrokeHistory> queryWrapper = createQueryWrapper(dto);
        UserStrokeHistory model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeHistoryDTO getOneDto(UserStrokeHistoryDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserStrokeHistory> getList(UserStrokeHistoryDTO dto) {
        final QueryWrapper<UserStrokeHistory> queryWrapper = createQueryWrapper(dto);
        final List<UserStrokeHistory> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserStrokeHistoryDTO> getListDto(UserStrokeHistoryDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeHistoryDTO> page(Page<UserStrokeHistory> page, UserStrokeHistoryDTO dto) {
        final QueryWrapper<UserStrokeHistory> queryWrapper = createQueryWrapper(dto, "us.");
        queryWrapper.orderByDesc("us.appointment_time");
        queryWrapper.orderByDesc("us.park_id");
        final IPage<UserStrokeHistoryDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(r -> r.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<WebUserStrokeDTO> webPage(Page<WebUserStrokeDTO> page, UserStrokeHistoryDTO dto) {
        final QueryWrapper<UserStrokeHistory> queryWrapper = createQueryWrapper(dto, "us.");
        UserOperatorService.buildInSql(dto, queryWrapper);
        queryWrapper.orderByDesc("us.start_time");
        queryWrapper.orderByAsc("us.park_id");
        final IPage<WebUserStrokeDTO> iPage = baseMapper.webPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(r -> r.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }


    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserStrokeHistory model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getSid()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, model.getUserId(), model.getTripType()));
    }

    /**
     * 清空最后一次行程的缓存
     *
     * @param userId 用户ID
     */
    public void clearLastCache(String userId) {
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, userId, DisplayUtil.TRIP_TYPE_0));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, userId, DisplayUtil.TRIP_TYPE_1));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_USER_ID, userId, DEFAULT_TRIP_TYPE));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserStrokeHistoryDTO modelToDto(UserStrokeHistory model) {
        if (null == model) {
            return null;
        }
        final UserStrokeHistoryDTO dto = new UserStrokeHistoryDTO();
        dto.setSid(model.getSid());
        dto.setNickName(model.getNickName());
        dto.setStartTime(model.getStartTime());
        dto.setAppointmentTime(model.getAppointmentTime());
        dto.setIntoTime(model.getIntoTime());
        dto.setOutTime(model.getOutTime());
        dto.setBillStartTime(model.getBillStartTime());
        dto.setBillEndTime(model.getBillEndTime());
        dto.setParkTime(model.getParkTime());
        dto.setAmount(model.getAmount());
        dto.setPayAmount(model.getPayAmount());
        dto.setOnLinePayAmount(model.getOnLinePayAmount());
        dto.setProcessStatus(model.getProcessStatus());
        dto.setParkId(model.getParkId());
        dto.setPlateNumber(model.getPlateNumber());
        dto.setUserId(model.getUserId());
        dto.setNote(model.getNote());
        dto.setStartTime(model.getStartTime());
        dto.setTripType(model.getTripType());
        dto.setStrongReservation(model.getStrongReservation());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserStrokeHistory dtoToModel(UserStrokeHistoryDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserStrokeHistory model = new UserStrokeHistory();
        model.setSid(dto.getSid());
        model.setNickName(dto.getNickName());
        model.setStartTime(dto.getStartTime());
        model.setAppointmentTime(dto.getAppointmentTime());
        model.setIntoTime(dto.getIntoTime());
        model.setOutTime(dto.getOutTime());
        model.setBillStartTime(dto.getBillStartTime());
        model.setBillEndTime(dto.getBillEndTime());
        model.setParkTime(dto.getParkTime());
        model.setAmount(dto.getAmount());
        model.setPayAmount(dto.getPayAmount());
        model.setOnLinePayAmount(dto.getOnLinePayAmount());
        model.setProcessStatus(dto.getProcessStatus());
        model.setParkId(dto.getParkId());
        model.setPlateNumber(dto.getPlateNumber());
        model.setUserId(dto.getUserId());
        model.setNote(dto.getNote());
        model.setTripType(dto.getTripType());
        model.setStrongReservation(dto.getStrongReservation());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    @SneakyThrows
    public void buildDisplay(UserStrokeHistoryDTO dto) {
        dto.setTripTypeDisplay(DisplayUtil.getTripTypeDisplay(dto.getTripType()));
        dto.setAmountDisplay(Optional.ofNullable(dto.getAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setOnLinePayAmountDisplay(Optional.ofNullable(dto.getOnLinePayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setProcessStatusDisplay(DisplayUtil.getProcessStatusDisplay(dto.getProcessStatus()));
        if (null != dto.getParkTime() && dto.getParkTime() > 0) {
            dto.setParkTimeDisplay(DisplayUtil.displayParkTime(dto.getParkTime()));
        }
        if (null == dto.getProcessDetails()) {
            final UserStrokeProcessDetail userStrokeProcessDetail = userStrokeProcessDetailService.getById(dto.getSid());
            if (null != userStrokeProcessDetail) {
                dto.setProcessDetails(objectMapper.readValue(userStrokeProcessDetail.getProcessDetails(), JsonNode.class));
            }
        }
        Map<String, String> parkInfo = new HashMap<>(16);
        final String address = Optional.ofNullable(carParkLocationService.getById(dto.getParkId())).map(CarParkLocation::getAddress).orElse("");
        final String parkSpaceType = Optional.ofNullable(carParkService.getById(dto.getParkId())).map(CarPark::getParkSpaceType).orElse("");
        parkInfo.put("address", address);
        parkInfo.put("parkSpaceType", parkSpaceType);
        dto.setParkInfo(parkInfo);
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    @SneakyThrows
    public void buildDisplay(WebUserStrokeDTO dto) {
        dto.setAmountDisplay(Optional.ofNullable(dto.getAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setOnLinePayAmountDisplay(Optional.ofNullable(dto.getOnLinePayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setProcessStatusDisplay(DisplayUtil.getProcessStatusDisplay(dto.getProcessStatus()));
        if (null != dto.getParkTime() && dto.getParkTime() > 0) {
            dto.setParkTimeDisplay(DisplayUtil.displayParkTime(dto.getParkTime()));
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserStrokeHistoryDTO> modelToDtoList(List<UserStrokeHistory> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserStrokeHistory> dtoToModelList(List<UserStrokeHistoryDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserStrokeHistory> createQueryWrapper(UserStrokeHistoryDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserStrokeHistory> createQueryWrapper(UserStrokeHistoryDTO dto, String tableAlias) {
        final QueryWrapper<UserStrokeHistory> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getParkId())) {
                queryWrapper.eq(tableAlias + "park_id", dto.getParkId());
            }
            if (StringUtils.hasLength(dto.getPlateNumber())) {
                queryWrapper.eq(tableAlias + "plate_number", dto.getPlateNumber());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (null != dto.getTripType()) {
                queryWrapper.eq(tableAlias + TRIP_TYPE, dto.getTripType());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<UserStrokeHistory> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserStrokeHistory> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserStrokeHistory::getSid).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }


}